package ygstudio.xue.de.edit;

import ygstudio.xue.de.R;
import android.os.Bundle;
import android.app.Fragment;
import android.graphics.Color;
import android.text.Html;
import android.text.Spannable;
import android.text.Spanned;
import android.text.style.BackgroundColorSpan;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

public class EditFragment extends Fragment {
	private EditText editText;
	private Spanned spanned;
	private String text = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.edit_fragment, container, false);
		editText = (EditText) view.findViewById(R.id.edit_text);
		if (spanned != null) {
			editText.setText(spanned);
		} else if (text != null) {
			editText.setText(text);
		}
		return view;
	}

	public void setHtml(String html) {
		spanned = Html.fromHtml(html);
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getHtml() {
		if (editText == null)
			return null;

		return Html.toHtml(editText.getEditableText());
	}

	public String getText() {
		if (editText == null)
			return null;

		return editText.getText().toString();
	}

	public void setBackgroundYellow() {
		setColor(new BackgroundColorSpan(Color.YELLOW));
	}

	public void setForegroundBlue() {
		setColor(new ForegroundColorSpan(Color.BLUE));
	}

	public void setForegroundRed() {
		setColor(new ForegroundColorSpan(Color.RED));
	}

	private void setColor(CharacterStyle cs) {
		int start = editText.getSelectionStart();
		int end = editText.getSelectionEnd();
		Spannable spannable = editText.getText();
		spannable.setSpan(cs, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
	}

	public void setForegroundBlack() {
		setColor(new ForegroundColorSpan(Color.BLACK));
	}

	public String getSelectedText() {
		int start = editText.getSelectionStart();
		int end = editText.getSelectionEnd();

		return editText.getText().toString().substring(start, end);
	}
}
